﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Tulde.Windows.Music
{
    public class XmlModelSerializer : IViewModelSerializer
    {
        #region IViewModelSerializer Members

        public string Serialize(object instance)
        {
            XmlSerializer xml = new XmlSerializer(instance.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                xml.Serialize(ms, instance);
                return System.Text.Encoding.ASCII.GetString(ms.ToArray());
            }
        }

        public T Deserialize<T>(string serializedInstance)
        {
            XmlSerializer xml = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream( Encoding.ASCII.GetBytes( serializedInstance) ))
            {
                return (T)xml.Deserialize(ms);
               
            }
        }

        public object Deserialize(Type type, string serializedInstance)
        {
            XmlSerializer xml = new XmlSerializer(type);
            using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(serializedInstance)))
            {
                return xml.Deserialize(ms);

            }
        }

        /// <summary>
        /// A utility method to serialize a viewmodel to a url query string parameter.  The url parameter name is derived from the full
        /// type of the viewmodel instance with each "." replaced by "_".
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public string SerializeToUrlParameter(object instance)
        {
            Guard.IsNotNull(instance);
            Type t = instance.GetType();
            string urlParameter = t.FullName.Replace(".", "_");
            return String.Format("{0}={1}", urlParameter, Serialize(instance));
        }
        /// <summary>
        /// Reads a key/value pair from the supplied IDictionary instance and attempts to deserialize the value into Type T.
        /// 
        /// The key is derived from the full type of (T)  with each "." replaced by "_".
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryStringParameters"></param>
        /// <returns></returns>
        public T DeserializeFromUrlParameter<T>(System.Collections.Generic.IDictionary<string, string> queryStringParameters)
        {
            Guard.IsNotNull(queryStringParameters);
            Type t = typeof(T);
            string urlParameter = t.FullName.Replace(".", "_");
            if (queryStringParameters.ContainsKey(urlParameter))
            {
                return this.Deserialize<T>(queryStringParameters[urlParameter]);
            }
            else
            {
                return default(T);
            }
        }

        #endregion
    }
}
